// miniprogram/pages/manager/editAbility/editAbility.js


const date = new Date()
const years = []
const months = []
const days = []
const hours = []
const minutes = []
var thisMon = date.getMonth();
var thisDay = date.getDate();
const db = wx.cloud.database()
for (let i = 2020; i <= date.getFullYear() + 1; i++) {
  years.push(i)
}

for (let i = 0; i <= 11; i++) {
  var k = i;
  if (0 <= i && i < 9) {
    k = "0" + (i + 1);
  } else {
    k = (i + 1);
  }
  months.push(k)
}
if (0 <= thisMon && thisMon < 9) {
  thisMon = "0" + (thisMon + 1);
} else {
  thisMon = (thisMon + 1);
}
if (0 <= thisDay && thisDay < 10) {
  thisDay = "0" + thisDay;
}

var totalDay = mGetDate(date.getFullYear(), thisMon);
for (let i = 1; i <= 31; i++) {
  var k = i;
  if (0 <= i && i < 10) {
    k = "0" + i
  }
  days.push(k)
}

for (let i = 0; i <= 23; i++) {
  var k = i;
  if (0 <= i && i < 10) {
    k = "0" + i
  }
  hours.push(k)
}
for (let i = 0; i <= 59; i++) {
  var k = i;
  if (0 <= i && i < 10) {
    k = "0" + i
  }
  minutes.push(k)
}
function mGetDate(year, month) {
  var d = new Date(year, month, 0);
  return d.getDate();
}


const app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    // 上传的案例图片集合
    cloudImages: [],
    uploadImages: [],
    // 设置上传案例图片的最大数目
    maxImages: 9,
    // 案例图片数目是否达到了最大数目

    Activity: {
      name: "",
      rule: "",
      prize: "",
      InformUrl: "",
      type: "",
      
      ApplyTimeStart: '2020-08-03',
      ApplyTimeEnd: '2020-08-03',
      ActivityTimeEnd: '2020-08-03',
      ActivityTimeStart: '2020-08-03',
      confirmxueyue: [],
      confirmnianji: [],
      uploadImages: [],
    },
    publish:[],
    isMaxImagesNum: false,

    val: [// 数据列表
      ['体育活动', '艺术活动', '学术活动', '其他活动'],

    ],
    isFocus: false,
    select: false,
    select2: false,
    type: '体育活动',
    Object: '体育活动',
    years: years,
    year: date.getFullYear(),
    months: months,
    month: thisMon,
    days: days,
    day: thisDay,
    value: [1, thisMon - 1, thisDay - 1, 0, 0],
    hours: hours,
    hour: "00",
    minutes: minutes,
    minute: "00",
    hidden: true,

    show: false,
    animationData: '',
    parameter: [{ id: 1, name: '银色' }, { id: 2, name: '白色' }, { id: 3, name: '黑色' }],
    confirmxueyue: [],
    confirmnianji: [],
    haveConfirm: false,
    gd1List2: [
      { name: "不限", isChecked2: false },
      { name: "人文学院", isChecked2: false },
      { name: "艺术学院", isChecked2: false },
      { name: "外国语学院", isChecked2: false },
      { name: "经管学院", isChecked2: false },
      { name: "数信学院", isChecked2: false },
      { name: "水利学院", isChecked2: false },
      { name: "食品学院", isChecked2: false },
      { name: "工程学院", isChecked2: false },
      { name: "生科学院", isChecked2: false },
      { name: "海洋学院", isChecked2: false },
      { name: "资环学院", isChecked2: false },
      { name: "动科学院", isChecked2: false },
      { name: "兽医学院", isChecked2: false },
      { name: "园艺学院", isChecked2: false },
      { name: "林风学院", isChecked2: false },
      { name: "农学院", isChecked2: false },
      // { name: "兽医学院", isChecked2: false },

    ],
    gd1List3: [
      { name: "不限", isChecked2: false },
      { name: "大一", isChecked2: false },
      { name: "大二", isChecked2: false },
      { name: "大三", isChecked2: false },
      { name: "大四", isChecked2: false },
      { name: "研究生", isChecked2: false },
    ],
    AbilityType: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.parameter[0].checked = true;
    this.setData({
      parameter: this.data.parameter,
    })//默认parameter数组的第一个对象是选中的

    console.log(this.data.Activity.ApplyTimeEnd)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindShowMsg() {
    this.setData({
      select: !this.data.select
    })
  },
  bindShowMsg2() {
    this.setData({
      select2: !this.data.select2
    })
  },
  mySelect(e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      type: name,
      select: false
    })
  },
  mySelect2(e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      Object: name,
      select2: false
    })
  },
  bindChange: function (e) {
    const val = e.detail.value
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]],
      hour: this.data.hours[val[3]],
      minute: this.data.minutes[val[4]],
    })
    var totalDay = mGetDate(this.data.year, this.data.month);
    var changeDate = [];
    for (let i = 1; i <= totalDay; i++) {
      var k = i;
      if (0 <= i && i < 10) {
        k = "0" + i
      }
      changeDate.push(k)
    }
    this.setData({
      days: changeDate
    })
  },
  handleFocus() {
    this.setData({
      hidden: false
    })
  },
  endFocus() {
    this.setData({
      hidden: true
    })
  },
  blockTime() {
    this.setData({
      hidden: false
    })
  },
  datePickerBindchange1: function (e) {
    this.setData({
      ['Activity.ActivityTimeStart']: e.detail.value
    })
  },

  datePickerBindchange2: function (e) {
    this.setData({
      ['Activity.ActivityTimeEnd']: e.detail.value
    })
  },
  datePickerBindchange3: function (e) {
    this.setData({
      ['Activity.ApplyTimeStart']: e.detail.value
    })
  },

  datePickerBindchange4: function (e) {
    this.setData({
      ['Activity.ApplyTimeEnd']: e.detail.value
    })
  },
  filter: function (e) { //点击筛选事件
    var animation = wx.createAnimation({//创建动画
      duration: 1000,
      timingFunction: 'ease',
      width: 300,
      height: 800,
      top: 0,
      bottom: 0,
      right: 0,
      backgroundColor: '#fff',
      opcity: 0.5
    })

    this.animation = animation

    animation.translateX(-100 + 'vh').step() //动画效果向右滑动100vh

    this.setData({
      animationData: animation.export(),
      show: true
    })
  },
  // 参数点击响应事件
  parameterTap: function (e) {//e是获取e.currentTarget.dataset.id所以是必备的，跟前端的data-id获取的方式差不多
    var that = this
    var this_checked = e.currentTarget.dataset.id
    var parameterList = this.data.parameter//获取Json数组
    for (var i = 0; i < parameterList.length; i++) {
      if (parameterList[i].id == this_checked) {
        parameterList[i].checked = true;//当前点击的位置为true即选中
      }
      else {
        parameterList[i].checked = false;//其他的位置为false
      }
    }
    that.setData({
      parameter: parameterList
    })
  },

  getDemo2: function (e) {

    var that = this

    var index = e.currentTarget.dataset.index;//每一个button的索引

    var item = that.data.gd1List2[index];//每一个索引对应的内容

    item.isChecked2 = !item.isChecked2;//选中，未选中 两种状态切换

    that.setData({//更新到data

      gd1List2: that.data.gd1List2,

    });

  },
  getDemo3: function (e) {

    var that = this

    var index = e.currentTarget.dataset.index;//每一个button的索引

    var item = that.data.gd1List3[index];//每一个索引对应的内容

    item.isChecked2 = !item.isChecked2;//选中，未选中 两种状态切换

    that.setData({//更新到data

      gd1List3: that.data.gd1List3,

    });

  },
  confirmSelect() {
    var that = this
    var array3 = that.data.gd1List3
    var array = that.data.gd1List2
    var array2 = []
    var array4 = []
    for (var i = 0; i < array.length; i++) {
      if (array[0].isChecked2 == true) {
        array2.push(array[i]);
        break;
      }

      if (array[i].isChecked2 == true) {

        array2.push(array[i]);
      }
    }
    for (var i = 0; i < array3.length; i++) {
      if (array3[0].isChecked2 == true) {
        array4.push(array3[i]);
        break;
      }

      if (array3[i].isChecked2 == true) {

        array4.push(array3[i]);
      }
    }
    // var that = this

    that.setData({
      show: false,
      // gd1List2: that.data.gd1List2,
      // gd1List3: that.data.gd1List3,
      confirmnianji: array4,
      confirmxueyue: array2,
      haveConfirm: true
    });

  },
  reverseSelect() {
    var that = this
    var array1 = that.data.gd1List2
    var array2 = that.data.gd1List3
    for (var i = 0; i < array1.length; i++) {
      if (array1[i].isChecked2 == true) {
        array1[i].isChecked2 = false
      }
    }
    for (var i = 0; i < array2.length; i++) {
      if (array2[i].isChecked2 == true) {
        array2[i].isChecked2 = false
      }
    }
    that.setData({
      gd1List2: array1,
      gd1List3: array2
    })
  },

  submit: function () {

    var activity = db.collection('AnotherAcitivity')

    if (this.data.AbilityType == "体育活动") {
      console.log("tiyu")
      activity = db.collection('SportActivity')

    }
    else if (this.data.AbilityType == "学术活动") {
      activity = db.collection('AcademicActivity')
    }
    else if (this.data.AbilityType == "艺术活动") {
      activity = db.collection('ArtActivity')
    }
    else {
      activity = db.collection('AnotherAcitivity')
    }

    this.data.Activity.type = this.data.AbilityType
    this.data.Activity.confirmnianji = this.data.confirmnianji
    this.data.Activity.confirmxueyue = this.data.confirmxueyue

    activity.add({
      // data 字段表示需新增的 JSON 数据
      data: {
        // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id，在此处场景下用数据库自动分配的就可以了

        Activity: this.data.Activity,
        publish1:this.data.publish,
        publish2:this.data.publish

      },
      success: function (res) {
        // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
        console.log(res);
        wx.navigateTo({
          url: '/pages/manager/success/success',
        })
      }
    })
  },
  addname: function (e) {
    this.setData({
      ['Activity.name']: e.detail.value
    })

  },
  addrule: function (e) {
    this.setData({
      ['Activity.rule']: e.detail.value
    })
  },

  addprize: function (e) {
    this.setData({
      ['Ativity.prize']: e.detail.value
    })
  },
  addurl: function (e) {
    this.setData({
      ['Activity.InformUrl']: e.detail.value
    })
  },
  finishHandler(e) {

    console.log(e.detail)// 选择的结果 如：["妖刀姬", "犬神"]
    this.setData({
      AbilityType: e.detail
    })
  },
  // 选择图片
  chooseImageTap: function () {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera')
          }
        }
      }
    })
  },

  // 选图
  chooseWxImage: function (type) {
    let _this = this;
    var picsItems;
    wx.chooseImage({
      // 相关属性设置
      count: _this.data.maxImages,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        // concat数组连接，且不会改变现有数组
        var picss = _this.data.uploadImages.concat(imgsrc);
        var imagesArr = '';
        if (picss.length >= _this.data.maxImages) {
          _this.setData({
            isMaxImagesNum: true
          });
        }
        // 判断选择的数量是否超过设定数量
        let num = picss.length <= _this.data.maxImages ? picss.length : _this.data.maxImages;
        for (var i = 0; i < num; i++) {
          imagesArr += '{"imgurl":"' + picss[i] + '"},';
        }
        imagesArr = JSON.parse('[' + imagesArr.substring(0, imagesArr.length - 1) + ']');
        _this.setData({
          uploadImages: picss,
          picsItems: imagesArr
        });
      },

    })

  },

  // 预览所选图片
  selImagePre: function (e) {
    let _this = this;
    var current = e.currentTarget.dataset.src
    wx.previewImage({
      urls: this.data.uploadImages,
      current
    })
    console.log(this.data.urls)
  },

  upload: function () {
    if (!this.data.uploadImages.length) {
      wx.showToast({
        icon: 'none',
        title: '图片类容为空'
      });
    } else {
      //上传图片到云存储
      wx.showLoading({
        title: '上传中',
      })
      let promiseArr = [];
      for (let i = 0; i < this.data.uploadImages.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          let item = this.data.uploadImages[i];
          let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
          let cloudPath = "Acitivity/" + app.globalData.openid + Date.now() + suffix;
          wx.cloud.uploadFile({
            cloudPath, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              this.setData({
                cloudImages: this.data.cloudImages.concat(res.fileID)
              });
              console.log(res.fileID)//输出上传后图片的返回地址
              reslove();
              wx.hideLoading();
              wx.showToast({
                title: "上传成功",
              })
            },
            fail: res => {
              wx.hideLoading();
              wx.showToast({
                title: "上传失败",
              })
            }

          })
        }));
      }
      Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
        console.log("图片上传完成后再执行")
        this.data.Activity.uploadImages = this.data.cloudImages
        this.submit()
      })

    }
  },
  toChange9:function(){

    const that = this
    wx.navigateTo({
      url: '../../user/edit/edit?editInform=9',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
         
        },
      },
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: that.data.Activity.rule})
      }
    });
  },
    toChange10:function(){
      const that = this
    wx.navigateTo({
      url: '../../user/edit/edit?editInform=10',
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function(data) {
         
        },
      },
      success: function(res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: that.data.Activity.prize})
      }
    });
  }


})